<template>
  <div>
    <el-input
            v-if="filter"
            clearable
            placeholder="输入关键字进行过滤"
            v-model="filterText"
    >
    </el-input>
    <el-tree
            :node-key="nodeKey"
            :show-checkbox="showCheckbox"
            ref="tree"
            :filter-node-method="filterNode"
            :default-expand-all="defaultExpandAll"
            :data="data"
            :props="defaultProps"
            @node-click="handleNodeClick"
    ></el-tree>
  </div>
</template>

<script>
  export default {
    name: "syxTree",
    props: {
      /**
       * 是否可选择
       */
      showCheckbox: {
        type: Boolean,
        default: () => false,
      },
      /**
       * 设置通过 key 获取的字段
       */
      nodeKey: {
        type: String,
        default: () => "",
      },
      /**
       * 是否有过滤
       */
      filter: {
        type: Boolean,
        default: () => true,
      },
      /**
       * 是否全部展开
       */
      defaultExpandAll: {
        type: Boolean,
        default: () => true,
      },
      /**
       * 默认文字展示/子列表
       */
      defaultProps: {
        type: Object,
        default: () => ({
          children: "children",
          label: "label",
        }),
      },
      /**
       * tree 树
       */
      data: {
        type: Array,
        default: () => [],
      },
    },
    data() {
      return {
        filterText: "",
      };
    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      },
    },
    methods: {
      /**
       * 获取 node 节点数据,只能获取子节点
       */
      getCheckedNodes() {
        return this.$refs.tree.getCheckedNodes();
      },
      /**
       * 获取 node 节点数据,只能获取父节点
       */
      getHalfCheckedNodes() {
        return this.$refs.tree.getHalfCheckedNodes();
      },
      /**
       * 获取 nodeKey 节点数据,只能获取子节点
       */
      getCheckedKeys() {
        return this.$refs.tree.getCheckedKeys();
      },
      /**
       * 获取 nodeKey 节点数据,只能获取父节点
       */
      getHalfCheckedKeys() {
        return this.$refs.tree.getHalfCheckedKeys();
      },
      /**
       * 获取 node 节点数据,获取父子节点
       */
      getNodes() {
        return this.getCheckedNodes().concat(this.getHalfCheckedNodes());
      },
      /**
       * 获取 nodeKey 节点数据,获取父子节点
       */
      getKeys() {
        return this.getCheckedKeys().concat(this.getHalfCheckedKeys());
      },
      /**
       * 过滤节点触发
       */
      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      /**
       * 点击节点触发
       * @param data
       */
      handleNodeClick(data) {
        this.$emit("handleNodeClick", data);
      },
    },
  };
</script>

<style></style>
